package com.lagou.service.impl;

import com.lagou.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author mcl
 * @date 2021/10/13 23:05
 * @description
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RedisTemplate redisTemplate;

    private final String PRODUCT_KEY = "products:count:";

    @Override
    public Long getCountById(Long productId) {
        Long count = Long.valueOf((String)redisTemplate.opsForValue().get(PRODUCT_KEY + productId)) ;
        if (null == count) {
            // TODO: 2021/10/13 read from database
            count = 10L;
            redisTemplate.opsForValue().set(PRODUCT_KEY + productId, String.valueOf(count),1, TimeUnit.DAYS);
        }
        return count;
    }

    @Override
    public Long incrementProductCount(Long productId) {
        // TODO: 2021/10/13 update to database
        return redisTemplate.opsForValue().increment(PRODUCT_KEY+productId);
    }

    @Override
    public Long decrementProductCount(Long productId) {
        // TODO: 2021/10/13 update to database
        return redisTemplate.opsForValue().decrement(PRODUCT_KEY+productId);
    }
}
